package org.example.order.service.impl;

import org.example.item.contract.request.ItemRequestForInventory;
import org.example.item.feign.ItemFeign;
import org.example.order.contract.request.OrderRequestForSave;
import org.example.order.model.entity.OrderInfo;
import org.example.order.model.entity.OrderItem;
import org.example.order.repository.OrderItemRepository;
import org.example.order.repository.OrderRepository;
import org.example.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ItemFeign itemFeign;
    @Autowired
    private OrderRepository orderRepository;

    private OrderItemRepository orderItemRepository;


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Long saveOrder(OrderRequestForSave request) {
        OrderInfo orderInfo = new OrderInfo();
        // 单号规则
        orderInfo.setOrderNo(getOrderNo());
        orderInfo.setAddress(request.getAddress());
        orderInfo.setRelatePhone(request.getTelPhone());
        BigDecimal totalPrice = BigDecimal.ZERO;
        List<OrderItem> itemList = new ArrayList<>();
        List<ItemRequestForInventory.Inventory> inventoryList = new ArrayList<>();
        for (OrderRequestForSave.ItemInfo item : request.getItems()) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(orderInfo.getOrderNo());
            orderItem.setCount(item.getCount());
            orderItem.setSkuNo(item.getSkuNo());
            orderItem.setUnitPrice(item.getUnitPrice());
            orderItem.setTotalPrice(item.getUnitPrice().multiply(BigDecimal.valueOf(item.getCount())));
            totalPrice = totalPrice.add(orderItem.getTotalPrice());

            inventoryList.add(new ItemRequestForInventory.Inventory(item.getSkuNo(), item.getCount()));
        }
        orderInfo.setTotalPrice(totalPrice);
        OrderInfo finalOrderInfo = orderRepository.save(orderInfo);
        itemList.stream().forEach(item -> item.setOrderId(finalOrderInfo.getId()));
        orderItemRepository.saveAll(itemList);
        /**
         * 扣减库存
         * todo  1. 异常透传
         * todo  2. 事务处理
         */
        itemFeign.deductInventory(new ItemRequestForInventory(inventoryList));
        return finalOrderInfo.getId();
    }

    private String getOrderNo() {
        return UUID.randomUUID().toString();
    }
}
